package com.chatmcp.mcprouter.service.impl;

import com.chatmcp.mcprouter.dto.ServerConfigDto;
import com.chatmcp.mcprouter.jsonrpc.*;
import com.chatmcp.mcprouter.service.McpClientService;
import com.chatmcp.mcprouter.util.HashUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;

/**
 * MCP客户端服务实现类
 * 负责与MCP服务器的通信
 */
@Slf4j
@Service
public class McpClientServiceImpl implements McpClientService {

    // 客户端类型枚举
    private enum ClientType {
        HTTP,
        PROCESS
    }

    private final ObjectMapper objectMapper;
    private final RestTemplate restTemplate;

    // 存储不同服务器的客户端信息
    private static final Map<String, ClientInfo> clientMap = new ConcurrentHashMap<>();
    
    // 存储共享进程的映射，键为命令哈希值，值为进程信息
    private static final Map<String, ProcessInfo> sharedProcessMap = new ConcurrentHashMap<>();
    
    // 进程监控执行器
    private static final ScheduledExecutorService processMonitor = Executors.newScheduledThreadPool(1);
    
    // 响应读取超时（毫秒）
    private static final long RESPONSE_TIMEOUT = 30000;
    
    // 进程健康检查间隔（毫秒）
    private static final long PROCESS_HEALTH_CHECK_INTERVAL = 60000;

    @Autowired
    public McpClientServiceImpl(ObjectMapper objectMapper, RestTemplate restTemplate) {
        this.objectMapper = objectMapper;
        this.restTemplate = restTemplate;
        
        // 启动进程监控任务
        startProcessMonitor();
    }

    /**
     * 启动进程监控任务
     */
    private void startProcessMonitor() {
        processMonitor.scheduleAtFixedRate(() -> {
            try {
                log.debug("Running process health check...");
                for (Map.Entry<String, ProcessInfo> entry : sharedProcessMap.entrySet()) {
                    String cmdHash = entry.getKey();
                    ProcessInfo processInfo = entry.getValue();
                    
                    // 检查进程是否存活
                    if (processInfo.process != null && !isProcessAlive(processInfo.process)) {
                        log.warn("Process {} is no longer alive, marking as inactive", cmdHash);
                        processInfo.isActive = false;
                        
                        // 通知所有使用此进程的客户端
                        for (ClientInfo client : clientMap.values()) {
                            if (client.process == processInfo.process) {
                                client.connected = false;
                                client.error = "Process terminated unexpectedly";
                            }
                        }
                        
                        // 尝试关闭资源
                        try {
                            closeProcessResources(processInfo);
                        } catch (Exception e) {
                            log.error("Error closing process resources: {}", e.getMessage());
                        }
                    }
                }
                
                // 清理不活跃的进程信息
                sharedProcessMap.entrySet().removeIf(entry -> !entry.getValue().isActive);
                
            } catch (Exception e) {
                log.error("Error in process monitor: {}", e.getMessage());
            }
        }, PROCESS_HEALTH_CHECK_INTERVAL, PROCESS_HEALTH_CHECK_INTERVAL, TimeUnit.MILLISECONDS);
    }
    
    /**
     * 检查进程是否存活
     */
    private boolean isProcessAlive(Process process) {
        try {
            process.exitValue();
            return false; // 如果能获取到退出值，说明进程已经结束
        } catch (IllegalThreadStateException e) {
            return true; // 如果抛出异常，说明进程仍在运行
        }
    }
    
    /**
     * 关闭进程相关资源
     */
    private void closeProcessResources(ProcessInfo processInfo) throws IOException {
        if (processInfo.writer != null) {
            processInfo.writer.close();
        }
        if (processInfo.reader != null) {
            processInfo.reader.close();
        }
        if (processInfo.process != null && isProcessAlive(processInfo.process)) {
            processInfo.process.destroy();
            // 等待一段时间后，如果进程仍未终止，则强制终止
            try {
                if (!processInfo.process.waitFor(5, TimeUnit.SECONDS)) {
                    processInfo.process.destroyForcibly();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.warn("Interrupted while waiting for process to terminate");
            }
        }
    }

    /**
     * 进程信息内部类
     */
    private static class ProcessInfo {
        private Process process;
        private OutputStreamWriter writer;
        private BufferedReader reader;
        private String commandHash;
        private boolean isActive;
        private LocalDateTime startTime;
        private int clientCount; // 使用此进程的客户端数量
    }

    /**
     * 客户端信息内部类
     */
    private static class ClientInfo {
        private ServerConfigDto serverConfig;
        private Process process;
        private OutputStreamWriter writer;
        private BufferedReader reader;
        private String error;
        private boolean connected;
        private ClientType clientType;
        private String serverUrl;
        private Consumer<String> notificationCallback;
        private String processKey; // 关联的进程键名（命令哈希值）
    }

    // 当前客户端信息
    private ClientInfo clientInfo;

    @Override
    public boolean connect(ServerConfigDto serverConfig) throws Exception {
        if (serverConfig == null) {
            throw new IllegalArgumentException("Server config cannot be null");
        }

        // 检查缓存中是否存在
        String cacheKey = serverConfig.getServerKey();
        clientInfo = clientMap.get(cacheKey);
        if (clientInfo != null && clientInfo.connected) {
            // 验证进程仍然存活（如果是进程类型）
            if (clientInfo.clientType == ClientType.PROCESS && 
                (clientInfo.process == null || !isProcessAlive(clientInfo.process))) {
                log.warn("Cached client process is no longer alive, reconnecting...");
                clientInfo.connected = false;
                // 继续创建新连接
            } else {
                return true;
            }
        }

        // 创建新的客户端信息
        clientInfo = new ClientInfo();
        clientInfo.serverConfig = serverConfig;
        clientInfo.error = null;
        clientInfo.connected = false;

        try {
            // 检查是本地服务器还是远程服务器
            if (serverConfig.getServerUrl() != null && !serverConfig.getServerUrl().isEmpty()) {
                // 远程服务器
                clientInfo.clientType = ClientType.HTTP;
                clientInfo.serverUrl = serverConfig.getServerUrl();
                clientInfo.connected = true;
            } else if (serverConfig.getCommand() != null && !serverConfig.getCommand().isEmpty()) {
                // 本地服务器
                clientInfo.clientType = ClientType.PROCESS;
                
                // 计算命令的哈希值作为进程的唯一标识
                String commandHash = HashUtil.md5(serverConfig.getCommand());
                clientInfo.processKey = commandHash;
                
                // 检查是否需要启动新进程
                boolean needNewProcess = true;
                
                // 如果配置了共享进程，则尝试复用已有进程
                if (Boolean.TRUE.equals(serverConfig.getShareProcess())) {
                    log.debug("Looking for shared process with hash: {}", commandHash);
                    
                    // 从共享进程映射中查找
                    ProcessInfo processInfo = sharedProcessMap.get(commandHash);
                    if (processInfo != null && processInfo.isActive && isProcessAlive(processInfo.process)) {
                        log.debug("Reusing existing shared process for command: {}", serverConfig.getCommand());
                        clientInfo.process = processInfo.process;
                        clientInfo.writer = processInfo.writer;
                        clientInfo.reader = processInfo.reader;
                        processInfo.clientCount++;
                        needNewProcess = false;
                    }
                    
                    // 如果没有找到共享进程，则继续检查客户端映射
                    if (needNewProcess) {
                        for (ClientInfo ci : clientMap.values()) {
                            if (ci.process != null && ci.connected && 
                                serverConfig.getCommand().equals(ci.serverConfig.getCommand()) && 
                                isProcessAlive(ci.process)) {
                                
                                log.debug("Reusing existing process from client for command: {}", serverConfig.getCommand());
                                clientInfo.process = ci.process;
                                clientInfo.writer = ci.writer;
                                clientInfo.reader = ci.reader;
                                clientInfo.processKey = ci.processKey;
                                
                                // 如果是第一次将此进程添加到共享映射
                                if (!sharedProcessMap.containsKey(commandHash)) {
                                    ProcessInfo newProcessInfo = new ProcessInfo();
                                    newProcessInfo.process = ci.process;
                                    newProcessInfo.writer = ci.writer;
                                    newProcessInfo.reader = ci.reader;
                                    newProcessInfo.commandHash = commandHash;
                                    newProcessInfo.isActive = true;
                                    newProcessInfo.startTime = LocalDateTime.now();
                                    newProcessInfo.clientCount = 2; // 当前客户端和原始客户端
                                    sharedProcessMap.put(commandHash, newProcessInfo);
                                } else {
                                    // 增加客户端计数
                                    ProcessInfo existingInfo = sharedProcessMap.get(commandHash);
                                    existingInfo.clientCount++;
                                }
                                
                                needNewProcess = false;
                                break;
                            }
                        }
                    }
                }

                if (needNewProcess) {
                    // 启动新进程
                    log.info("Starting new process for command: {}", serverConfig.getCommand());
                    ProcessBuilder pb = new ProcessBuilder();
                    if (System.getProperty("os.name").toLowerCase().contains("win")) {
                        pb.command("cmd.exe", "/c", serverConfig.getCommand());
                    } else {
                        pb.command("sh", "-c", serverConfig.getCommand());
                    }
                    
                    // 配置错误输出重定向
                    File errorLog = new File("mcp_error_" + commandHash + ".log");
                    pb.redirectError(errorLog);
                    
                    Process process = pb.start();
                    OutputStreamWriter writer = new OutputStreamWriter(process.getOutputStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    
                    clientInfo.process = process;
                    clientInfo.writer = writer;
                    clientInfo.reader = reader;
                    
                    // 如果配置了共享进程，则添加到共享进程映射
                    if (Boolean.TRUE.equals(serverConfig.getShareProcess())) {
                        ProcessInfo processInfo = new ProcessInfo();
                        processInfo.process = process;
                        processInfo.writer = writer;
                        processInfo.reader = reader;
                        processInfo.commandHash = commandHash;
                        processInfo.isActive = true;
                        processInfo.startTime = LocalDateTime.now();
                        processInfo.clientCount = 1;
                        sharedProcessMap.put(commandHash, processInfo);
                    }
                    
                    // 读取初始输出
                    readProcessOutput();
                    
                    // 启动异步进程监控
                    monitorProcessAsync(process, commandHash);
                }
                clientInfo.connected = true;
            } else {
                throw new IllegalArgumentException("Either server URL or command must be provided");
            }

            // 初始化连接
            if (clientInfo.connected) {
                // 发送initialize请求
                InitializeParams params = new InitializeParams();
                params.setProtocolVersion("1.0");
                InitializeParams.ClientInfo ciParams = new InitializeParams.ClientInfo();
                ciParams.setName("Java MCP Router");
                ciParams.setVersion("1.0.0");
                params.setClientInfo(ciParams);

                JsonRpcRequest request = new JsonRpcRequest();
                request.setJsonrpc(JsonRpcConstants.JSONRPC_VERSION);
                request.setMethod(JsonRpcConstants.Method.INITIALIZE);
                request.setParams(objectMapper.valueToTree(params));
                request.setId(UUID.randomUUID().toString());

                JsonRpcResponse response = sendRequest(request);
                if (response == null || response.getError() != null) {
                    clientInfo.error = response != null ? 
                        response.getError().getMessage() : "Failed to initialize connection";
                    clientInfo.connected = false;
                    
                    // 处理初始化失败的情况
                    if (clientInfo.clientType == ClientType.PROCESS && 
                        Boolean.TRUE.equals(serverConfig.getShareProcess())) {
                        // 从共享进程映射中减少计数或移除
                        decrementProcessClientCount(clientInfo.processKey);
                    }
                    
                    return false;
                }
                
                clientMap.put(cacheKey, clientInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("Failed to connect to MCP server: {}", e.getMessage());
            clientInfo.error = e.getMessage();
            clientInfo.connected = false;
            
            // 处理连接失败的情况
            if (clientInfo.clientType == ClientType.PROCESS && 
                Boolean.TRUE.equals(serverConfig.getShareProcess()) && 
                clientInfo.processKey != null) {
                // 从共享进程映射中减少计数或移除
                decrementProcessClientCount(clientInfo.processKey);
            }
            
            return false;
        }
    }
    
    /**
     * 减少进程客户端计数，如果计数为0则移除进程信息
     */
    private void decrementProcessClientCount(String processKey) {
        if (processKey == null) return;
        
        ProcessInfo processInfo = sharedProcessMap.get(processKey);
        if (processInfo != null) {
            processInfo.clientCount--;
            log.debug("Decreased client count for process {}: now {}", processKey, processInfo.clientCount);
            
            if (processInfo.clientCount <= 0) {
                // 尝试关闭进程资源
                try {
                    closeProcessResources(processInfo);
                } catch (Exception e) {
                    log.error("Error closing process resources: {}", e.getMessage());
                }
                
                // 从映射中移除
                sharedProcessMap.remove(processKey);
                log.debug("Removed process from shared map: {}", processKey);
            }
        }
    }
    
    /**
     * 异步监控进程状态
     */
    private void monitorProcessAsync(Process process, String commandHash) {
        CompletableFuture.runAsync(() -> {
            try {
                // 等待进程结束
                int exitCode = process.waitFor();
                log.info("Process with hash {} exited with code {}", commandHash, exitCode);
                
                // 更新进程状态
                ProcessInfo processInfo = sharedProcessMap.get(commandHash);
                if (processInfo != null) {
                    processInfo.isActive = false;
                    
                    // 通知所有使用此进程的客户端
                    for (ClientInfo client : clientMap.values()) {
                        if (client.process == process) {
                            client.connected = false;
                            client.error = "Process terminated with exit code " + exitCode;
                        }
                    }
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.warn("Process monitor thread interrupted");
            }
        });
    }

    @Override
    public void close() {
        if (clientInfo != null) {
            try {
                if (clientInfo.clientType == ClientType.PROCESS && clientInfo.process != null) {
                    if (Boolean.TRUE.equals(clientInfo.serverConfig.getShareProcess()) && 
                        clientInfo.processKey != null) {
                        // 共享进程，减少计数而不是直接关闭
                        decrementProcessClientCount(clientInfo.processKey);
                    } else {
                        // 非共享进程，直接关闭
                        clientInfo.process.destroy();
                        // 等待进程终止
                        try {
                            if (!clientInfo.process.waitFor(5, TimeUnit.SECONDS)) {
                                clientInfo.process.destroyForcibly();
                            }
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                        
                        if (clientInfo.writer != null) {
                            clientInfo.writer.close();
                        }
                        if (clientInfo.reader != null) {
                            clientInfo.reader.close();
                        }
                    }
                }
            } catch (Exception e) {
                log.error("Error closing client connection: {}", e.getMessage());
            } finally {
                clientInfo.connected = false;
            }
        }
    }

    @Override
    public boolean isConnected() {
        if (clientInfo == null) {
            return false;
        }
        
        // 对于进程类型客户端，额外检查进程是否仍在运行
        if (clientInfo.clientType == ClientType.PROCESS && clientInfo.process != null) {
            return clientInfo.connected && isProcessAlive(clientInfo.process);
        }
        
        return clientInfo.connected;
    }

    @Override
    public String getError() {
        return clientInfo != null ? clientInfo.error : null;
    }

    @Override
    public void setNotificationCallback(Consumer<String> callback) {
        if (clientInfo != null) {
            clientInfo.notificationCallback = callback;
        }
    }

    /**
     * 读取进程响应，支持超时
     *
     * @return 响应字符串，如果超时则返回null
     * @throws Exception 如果读取失败
     */
    private String readResponseWithTimeout() throws Exception {
        if (clientInfo == null || clientInfo.reader == null) {
            throw new IllegalStateException("Client not initialized");
        }
        
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(() -> {
            StringBuilder response = new StringBuilder();
            int braceCount = 0;
            boolean inString = false;
            boolean escape = false;
            int c;
            
            // 读取一个完整的JSON对象
            while ((c = clientInfo.reader.read()) != -1) {
                char ch = (char) c;
                response.append(ch);
                
                if (escape) {
                    escape = false;
                } else if (ch == '\\' && inString) {
                    escape = true;
                } else if (ch == '"') {
                    inString = !inString;
                } else if (!inString) {
                    if (ch == '{') {
                        braceCount++;
                    } else if (ch == '}') {
                        braceCount--;
                        if (braceCount == 0) {
                            break; // 完整JSON对象读取完毕
                        }
                    }
                }
            }
            
            return response.toString();
        });
        
        try {
            return future.get(RESPONSE_TIMEOUT, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            future.cancel(true);
            log.error("Timeout reading response from process");
            return null;
        } finally {
            executor.shutdownNow();
        }
    }

    @Override
    public JsonRpcResponse forwardMessage(JsonRpcRequest request) throws Exception {
        // 调用新的统一方法处理请求
        return sendRequest(request);
    }

    @Override
    public boolean notificationsInitialized() throws Exception {
        if (!isConnected()) {
            throw new IllegalStateException("Client is not connected");
        }
        
        // 发送"notifications/initialized"通知
        JsonRpcRequest request = new JsonRpcRequest();
        request.setJsonrpc(JsonRpcConstants.JSONRPC_VERSION);
        request.setMethod("notifications/initialized");
        request.setParams(null);
        
        // 由于这是通知，不需要等待响应
        String requestJson = objectMapper.writeValueAsString(request);
        
        if (clientInfo.clientType == ClientType.HTTP) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);
            restTemplate.exchange(clientInfo.serverUrl, HttpMethod.POST, entity, String.class);
        } else if (clientInfo.clientType == ClientType.PROCESS) {
            clientInfo.writer.write(requestJson + "\n");
            clientInfo.writer.flush();
        }
        
        return true;
    }

    @Override
    public List<Tool> listTools() throws Exception {
        if (!isConnected()) {
            throw new IllegalStateException("Client is not connected");
        }
        
        // 发送"tools/list"请求
        JsonRpcRequest request = new JsonRpcRequest();
        request.setJsonrpc(JsonRpcConstants.JSONRPC_VERSION);
        request.setMethod("tools/list");
        request.setParams(null);
        request.setId(UUID.randomUUID().toString());
        
        JsonRpcResponse response = sendRequest(request);
        if (response == null || response.getError() != null) {
            if (response != null && response.getError() != null) {
                throw new Exception("Failed to list tools: " + response.getError().getMessage());
            } else {
                throw new Exception("Failed to list tools");
            }
        }
        
        // 解析工具列表
        try {
            return objectMapper.convertValue(response.getResult(), 
                    objectMapper.getTypeFactory().constructCollectionType(List.class, Tool.class));
        } catch (Exception e) {
            throw new Exception("Failed to parse tools list: " + e.getMessage());
        }
    }

    @Override
    public Tool.CallToolResult callTool(String name, Object arguments) throws Exception {
        if (!isConnected()) {
            throw new IllegalStateException("Client is not connected");
        }
        
        if (name == null || name.isEmpty()) {
            throw new IllegalArgumentException("Tool name cannot be null or empty");
        }
        
        // 创建工具调用参数
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("arguments", arguments != null ? arguments : Collections.emptyMap());
        
        // 发送"tools/call"请求
        JsonRpcRequest request = new JsonRpcRequest();
        request.setJsonrpc(JsonRpcConstants.JSONRPC_VERSION);
        request.setMethod("tools/call");
        request.setParams(objectMapper.valueToTree(params));
        request.setId(UUID.randomUUID().toString());
        
        JsonRpcResponse response = sendRequest(request);
        if (response == null || response.getError() != null) {
            if (response != null && response.getError() != null) {
                throw new Exception("Failed to call tool: " + response.getError().getMessage());
            } else {
                throw new Exception("Failed to call tool");
            }
        }
        
        // 解析工具调用结果
        try {
            return objectMapper.convertValue(response.getResult(), Tool.CallToolResult.class);
        } catch (Exception e) {
            throw new Exception("Failed to parse tool call result: " + e.getMessage());
        }
    }

    /**
     * 发送请求到MCP服务器并等待响应
     *
     * @param request JSON-RPC请求
     * @return JSON-RPC响应
     * @throws Exception 如果发送失败
     */
    @Override
    public JsonRpcResponse sendRequest(JsonRpcRequest request) throws Exception {
        if (!isConnected()) {
            throw new IllegalStateException("Client is not connected");
        }
        
        if (request == null) {
            return JsonRpcResponse.invalidRequest("JSON-RPC request cannot be null");
        }
        
        // 发送请求
        String requestJson = objectMapper.writeValueAsString(request);
        
        // 使用不同的实现方式处理请求
        if (clientInfo.clientType == ClientType.HTTP) {
            // 处理HTTP请求
            try {
                log.debug("Sending HTTP request: {}", requestJson);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                
                HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);
                ResponseEntity<String> response = restTemplate.exchange(
                        clientInfo.serverUrl,
                        HttpMethod.POST,
                        entity,
                        String.class
                );
                
                if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                    try {
                        JsonRpcResponse jsonRpcResponse = objectMapper.readValue(response.getBody(), JsonRpcResponse.class);
                        log.debug("Received HTTP response: {}", jsonRpcResponse);
                        return jsonRpcResponse;
                    } catch (Exception e) {
                        log.error("Failed to parse HTTP response: {}", e.getMessage(), e);
                        return JsonRpcResponse.parseError(request.getId());
                    }
                } else {
                    log.error("HTTP request failed: {}", response.getStatusCode());
                    return JsonRpcResponse.internalError(request.getId(), "HTTP request failed: " + response.getStatusCode());
                }
            } catch (Exception e) {
                log.error("Failed to send HTTP request: {}", e.getMessage(), e);
                clientInfo.error = "Failed to send HTTP request: " + e.getMessage();
                return JsonRpcResponse.internalError(request.getId(), clientInfo.error);
            }
        } else if (clientInfo.clientType == ClientType.PROCESS) {
            // 处理进程请求
            try {
                log.debug("Sending process request: {}", requestJson);
                
                if (clientInfo.process == null || !clientInfo.process.isAlive()) {
                    log.error("Process is not running");
                    return JsonRpcResponse.internalError(request.getId(), "Process is not running");
                }
                
                // 发送请求
                clientInfo.writer.write(requestJson + "\n");
                clientInfo.writer.flush();
                
                // 读取响应（使用超时防止阻塞）
                String responseJson = readResponseWithTimeout();
                if (responseJson == null) {
                    log.error("Failed to read response from process");
                    return JsonRpcResponse.internalError(request.getId(), "Failed to read response from process");
                }
                
                try {
                    JsonRpcResponse jsonRpcResponse = objectMapper.readValue(responseJson, JsonRpcResponse.class);
                    log.debug("Received process response: {}", jsonRpcResponse);
                    return jsonRpcResponse;
                } catch (Exception e) {
                    log.error("Failed to parse process response: {}", e.getMessage(), e);
                    return JsonRpcResponse.parseError(request.getId());
                }
            } catch (Exception e) {
                log.error("Failed to send process request: {}", e.getMessage(), e);
                clientInfo.error = "Failed to send process request: " + e.getMessage();
                return JsonRpcResponse.internalError(request.getId(), clientInfo.error);
            }
        } else {
            clientInfo.error = "Unsupported client type";
            log.error(clientInfo.error);
            return JsonRpcResponse.internalError(request.getId(), clientInfo.error);
        }
    }

    /**
     * 读取进程的初始输出
     */
    private void readProcessOutput() {
        if (clientInfo == null || clientInfo.reader == null) {
            return;
        }
        
        try {
            // 非阻塞方式读取进程输出
            if (clientInfo.reader.ready()) {
                String line = clientInfo.reader.readLine();
                log.debug("Process output: {}", line);
            }
        } catch (Exception e) {
            log.warn("Error reading process output: {}", e.getMessage());
        }
    }

    @Override
    public void disconnect() {
        if (clientInfo != null) {
            try {
                // Send a disconnect notification if needed
                // But don't close the websocket connection completely yet
                clientInfo.connected = false;
                log.debug("Disconnected from MCP server");
            } catch (Exception e) {
                log.error("Error disconnecting from MCP server: {}", e.getMessage());
            }
        }
    }
} 